import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image,
    Dimensions,
    ListView,
    TouchableOpacity
} from 'react-native';
import Config from '../common/Config'
import Utils from '../common/Utils'
import {Toast,ModalIndicator} from 'teaset';
import TitleBar from '../views/TitleBar';
import StorageUtil from '../StorageUtil';
import ConversationUtil from '../ConversationUtil';
import UserInfoUtil from '../UserInfoUtil';
import TimeUtil from '../TimeUtil';
const {height, width} = Dimensions.get('window');
import CountEmitter from '../event/CountEmitter';
export default class NewsTabPage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isShow:false,
            recentConversation: []
        };
        this.registerHXListener();
    };
    loadConversations(username) {
        ConversationUtil.getConversations(username, (result) => {
            let count = result.length;
            let index = 0;
            for (let i = 0; i < count; i++) {
                let conversation = result[i];
                let chatWithUsername = conversation.conversationId.replace(username, '');
                UserInfoUtil.getUserInfo(chatWithUsername, (userInfo) => {
                    index++;
                    if (userInfo != null) {
                        conversation['avatar'] = userInfo.avatar;
                        conversation['nick'] = userInfo.nick;
                    }
                    if (index == count) {
                        this.setState({recentConversation: result});
                        ConversationUtil.showConversations();
                    }
                });
            }
        });
    }

    registerHXListener() {  // 注册环信的消息监听器
        WebIM.conn.listen({
            // xmpp连接成功
            onOpened: (msg) => {
                Toast.message('onOpend')
                // 登录环信服务器成功后回调这里
                // 出席后才能接受推送消息
                WebIM.conn.setPresence();
            },
            // 出席消息
            onPresence: (msg) => {
            },
            // 各种异常
            onError: (error) => {
                Toast.message('登录聊天服务器出错');
                console.log('onError: ' + JSON.stringify(error));
            },
            // 连接断开
            onClosed: (msg) => {
                Toast.message('与聊天服务器连接断开');
            },
            // 更新黑名单
            onBlacklistUpdate: (list) => {
            },
            // 文本消息
            onTextMessage: (message) => {
                message.conversationId = ConversationUtil.generateConversationId(message.from, message.to);
                message.msgType = 'txt';
                message.time = TimeUtil.currentTime();
                ConversationUtil.addMessage(message, (error) => {
                    // 重新加载会话
                    this.loadConversations(this.state.username);
                    // 若当前在聊天界面，还要通知聊天界面刷新
                    CountEmitter.emit('notifyChattingRefresh');
                });
            },
            onPictureMessage: (message) => {
                message.conversationId = ConversationUtil.generateConversationId(message.from, message.to);
                message.msgType = 'img';
                message.time = TimeUtil.currentTime();
                ConversationUtil.addMessage(message, (error) => {
                    // 重新加载会话
                    this.loadConversations(this.state.username);
                    // 若当前在聊天界面，还要通知聊天界面刷新
                    CountEmitter.emit('notifyChattingRefresh');
                });
            }
        });
    }
    goToPage=(page)=>{
        this.setState({
            isShow:false
        },()=>{
            Actions.push(page)
        })
    };

    render() {
        return (
            <View style={styles.container}>
                {this.state.isShow
                ?(<TouchableOpacity
                        onPress={()=>this.setState({
                            isShow:false
                        })}
                        style={{position: 'absolute',top:0,bottom:0,left:0,right:0,
                            backgroundColor:'rgba(0,0,0,0)',zIndex:2}}>
                        <View style={styles.showView}>
                            <View style={{flexDirection:'row'}}>
                                <View style={styles.triangleLeft}/>
                                <View style={styles.triangleRight}/>
                            </View>
                            <View style={{backgroundColor:'#000000',width:110,height:69,borderRadius:5}}>
                                <TouchableOpacity
                                    onPress={()=>this.goToPage('QueryFriendsPage')}
                                    style={{alignItems:'center',flexDirection:'row',height:34,width:110}}>
                                    <Image
                                        source={ImageUtil.Upload}
                                        style={{marginLeft:14,height:18,width:18}}/>
                                    <Text style={{fontSize:14,marginLeft:12,color:'#ffffff'}}>添加好友</Text>
                                </TouchableOpacity>
                                <View style={{height:1,width:100,backgroundColor:'#ffffff',marginLeft:5}}/>
                                <TouchableOpacity
                                    onPress={()=>this.goToPage()}
                                    style={{ alignItems:'center',flexDirection:'row',height:34,width:110}}>
                                    <Image
                                        source={ImageUtil.AddLending}
                                        style={{marginLeft:14,height:18,width:18}}/>
                                    <Text style={{fontSize:14,marginLeft:12,color:'#ffffff'}}>发起群聊</Text>
                                </TouchableOpacity>
                            </View>
                        </View>
                    </TouchableOpacity>)
                :(null)}
                <View style={styles.titleView}>
                    <Text style={styles.titleMsg}>消息</Text>
                    <TouchableOpacity
                        onPress={()=>this.setState({
                            isShow:true
                        })}
                        style={styles.titleImgView}>
                        <Image
                            style={styles.titleImg}
                            source={ImageUtil.adjunctionWhite}/>
                    </TouchableOpacity>
                </View>
                <TouchableOpacity style={styles.labelView}>
                    <Image
                        style={styles.labelImg}
                        source={ImageUtil.CustomerService}/>
                    <Text style={styles.labelMsg}>信用客服0574</Text>
                </TouchableOpacity>
                <TouchableOpacity
                    onPress={()=>Actions.ChatMessagesPage()}
                    style={styles.labelChangeView}>
                    <Image style={{height:44,width:44,marginLeft:15,borderRadius:5,backgroundColor:'#f0f0f0',marginTop:23/2,marginBottom:23/2}}/>
                    <View style={{marginLeft:14}}>
                        <Text style={{fontSize:16,color:'#000000'}}>0574区域聊天室</Text>
                        <Text style={{fontSize:14,color:'#646464',marginTop:11}}>慈溪区域聊天室</Text>
                    </View>
                </TouchableOpacity>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor:'#f0f0f0'
    },
    titleView:{
        backgroundColor:'#000000',
        width:width,
        alignItems:'center',
        justifyContent:'center'
    },
    titleMsg:{
        textAlign:'center',
        fontSize:20,
        color:'#ffffff',
        marginTop:34,
        marginBottom:14
    },
    titleImgView:{
        position: 'absolute',
        right:15,
        bottom:25/2,
    },
    labelView:{
        height:45,
        width:width,
        backgroundColor:'#ffffff',
        borderBottomWidth:1,
        borderTopWidth:1,
        borderColor:'#e3e3e4',
        marginTop:5,
        flexDirection:'row',
        alignItems:'center'
    },
    labelChangeView:{
        width:width,
        backgroundColor:'#ffffff',
        borderBottomWidth:1,
        borderTopWidth:1,
        borderColor:'#e3e3e4',
        marginTop:5,
        alignItems:'center',
        flexDirection:'row'
    },
    labelImg:{
        marginLeft:15,
        width:30,
        height:30,
        borderRadius:5
    },
    labelMsg:{
        marginLeft:19,
        fontSize:14,
        color:'#000000'
    },
    showView:{
        position: 'absolute',
        top:68,right:15,zIndex:5,
        width:110,
        borderRadius:5,
        opacity:1
    },
    triangleLeft:{
        width: 0,
        height: 0,
        backgroundColor: 'rgba(0,0,0,0)',
        borderStyle: 'solid',
        borderLeftWidth: 6,
        borderRightWidth: 6,
        borderBottomWidth: 8,
        borderTopWidth: 8,
        borderLeftColor: 'transparent',
        borderRightColor: '#000000',
        borderTopColor: 'transparent',
        borderBottomColor: '#000000',
        marginLeft:80
    },
    triangleRight:{
        width: 0,
        height: 0,
        backgroundColor: 'rgba(0,0,0,0)',
        borderStyle: 'solid',
        borderLeftWidth: 6,
        borderRightWidth: 6,
        borderBottomWidth: 8,
        borderTopWidth: 8,
        borderLeftColor: '#000000',
        borderRightColor: 'transparent',
        borderTopColor: 'transparent',
        borderBottomColor: '#000000',
    }
});
